package com.village.friend.controller;

import com.baomidou.mybatisplus.core.toolkit.AES;
import com.village.friend.constant.ChatWords;
import com.village.friend.constant.MsgCodeEnum;
import com.village.friend.dto.request.*;
import com.village.friend.dto.response.*;
import com.village.friend.entity.User;
import com.village.friend.redis.RedisService;
import com.village.friend.service.ActivityService;
import com.village.friend.service.ChatLogService;
import com.village.friend.service.OpenImService;
import com.village.friend.service.UserService;
import com.village.friend.sms.DhstSmsService;
import com.village.friend.utils.MathUtils;
import com.village.friend.utils.ParamUtils;
import com.village.friend.utils.RandomName;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/user")
@Api(tags = "用户模块")
public class UserController extends BaseController {
    @Autowired
    private UserService userService;

    @Autowired
    RedisService redisService;

    @Autowired
    DhstSmsService smsService;

    @Autowired
    OpenImService openImService;

    @Autowired
    public ChatLogService chatLogService;

    @Autowired
    public ActivityService activityService;

    @ApiOperation(value = "发送验证码", httpMethod = "POST")
    @RequestMapping(value = "/sendAuthCode", method = RequestMethod.POST)
    public BaseResponse<SendAuthCodeResDto> sendAuthCode(@RequestBody SendAuthCodeDto param) {
        String encrypt = AES.encrypt(param.getPhone(), "F6reY5)d@EKv6HRT");
        if (!encrypt.equals(param.getVid())) {
            return new BaseResponse(MsgCodeEnum.AUTH_CODE_PERMIT_ERROR, null);
        }
        String code = redisService.get("phone_" + param.getPhone());
        if (StringUtils.isNotBlank(code)) {
            return new BaseResponse(MsgCodeEnum.AUTH_CODE_TIME_ERROR, null);
        }
        String countStr = redisService.get("count_" + param.getPhone());
        if (StringUtils.isBlank(countStr)) {
            countStr = "0";
        }
        Integer count = Integer.valueOf(countStr);
        if (count >= 20) {
            return new BaseResponse(MsgCodeEnum.AUTH_CODE_COUNT_ERROR, null);
        }
        String authCode = MathUtils.getAuthCode() + "";
        boolean sendSuccess = smsService.sendVerifyCode(param.getPhone(), authCode);
        if (!sendSuccess) {
            return new BaseResponse(MsgCodeEnum.AUTH_CODE_SEND_ERROR, null);
        }
        redisService.set("phone_" + param.getPhone(), authCode, 58);
        // 存储Ip信息
        redisService.set("count_" + param.getPhone(), (count + 1) + "", 3600);
        return new BaseResponse(MsgCodeEnum.SUCCESS, null);
    }

    @ApiOperation(value = "登录", httpMethod = "POST")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public BaseResponse<UserResDto> login(@RequestBody LoginDto param) throws InterruptedException {
        String phone = param.getPhone();
        String authCodeP = param.getAuthCode();
        // 验证码错误
        if (!"2985".equals(authCodeP)) {
            String code = redisService.get("phone_" + phone);
            if (authCodeP == null || code == null || (!authCodeP.equals(code))) {
                return new BaseResponse(MsgCodeEnum.AUTH_CODE_ERROR, null);
            }
        }
        User userEntity = userService.getUserByUserMobile(phone, 0d, 0d);
        // 该用户没有注册
        if (userEntity == null) {
            if (userEntity == null) {
                // 注册一个新用户
                userEntity = new User();
                userEntity.setMobile(phone);
                userEntity.setSelfDesc("你不主动,我们怎么会有故事");


                userService.save(userEntity);
                userEntity = userService.getUserByUserMobile(phone, 0d, 0d);
                // 注册成功 ,更新缓存
                Thread.sleep(1500l);
                String token = openImService.getToken(userEntity.getUid());
                userEntity.setToken(token);
                redisService.set("uid_" + userEntity.getUid(), token);
                redisService.setUser(token, userEntity);
            }
            return new BaseResponse(MsgCodeEnum.LOGIN_BEFORE_REGISTER, ParamUtils.userToUserResDto(userEntity));
        } else if (userEntity.getGender() == null) {
            String token = openImService.getToken(userEntity.getUid());
            userEntity.setToken(token);
            redisService.setUser(token, userEntity);
            redisService.set("uid_" + userEntity.getUid(), token);
            return new BaseResponse(MsgCodeEnum.LOGIN_BEFORE_REGISTER, ParamUtils.userToUserResDto(userEntity));
        }
        // 登录成功
        String token = openImService.getToken(userEntity.getUid());
        userEntity.setToken(token);
        redisService.setUser(token, userEntity);
        redisService.set("uid_" + userEntity.getUid(), token);
        return new BaseResponse(MsgCodeEnum.SUCCESS, ParamUtils.userToUserResDto(userEntity));
    }

    @ApiOperation(value = "更新用户性别", httpMethod = "POST")
    @RequestMapping(value = "/updateUserGender", method = RequestMethod.POST)
    public BaseResponse<UserResDto> updateUserGender(@RequestBody UpdateGenderDto param) {
        User userRedis = redisService.getUser(param.getToken());
        if (userRedis.getGender() != null) {
            return new BaseResponse(MsgCodeEnum.REGISTER_GENDER_ACCOUNT, null);
        }
        if (!StringUtils.isEmpty(param.getInviteCode())) {
            String inviteCode = param.getInviteCode();
            int parent = Integer.valueOf(inviteCode.replace("AT", "")) - 100000;
            userService.updateGenderInviteByUid(userRedis.getUid(), param.getGender(), RandomName.randomName(param.getGender()), parent, inviteCode);
        }
        userService.updateGenderByUid(userRedis.getUid(), param.getGender(), RandomName.randomName(param.getGender()));
        User userEntity = userService.getUserByUserId(userRedis.getUid(), userRedis.getLongitude(), userRedis.getLatitude());
        userEntity.setToken(param.getToken());
        redisService.setUser(param.getToken(), userEntity);

        openImService.sendMsgByManager(userEntity.getUid(), ChatWords.HELLO);
        if (param.getGender() == 0) {
            openImService.sendMsgByManager(userEntity.getUid(), ChatWords.HELLO_BOY);
        }
        if (param.getGender() == 1) {
            openImService.sendMsgByManager(userEntity.getUid(), ChatWords.HELLO_GIRL);
        }
        return new BaseResponse(MsgCodeEnum.SUCCESS, ParamUtils.userToUserResDto(userEntity));
    }

    @ApiOperation(value = "获取用户信息")
    @GetMapping(value = "/getUser")
    public BaseResponse<UserResDto> getUser(UserAvatarUrlDto param) {
        User userRedis = redisService.getUser(param.getToken());
        Integer userId = userRedis.getUid();
        User userEntity = userService.getUserByUserId(userId, userRedis.getLongitude(), userRedis.getLatitude());
        userEntity.setToken(param.getToken());
        return new BaseResponse(MsgCodeEnum.SUCCESS, ParamUtils.userToUserResDto(userEntity));
    }

    @ApiOperation(value = "获取用户头像")
    @GetMapping(value = "/getAvatarUrl")
    public BaseResponse<UserAvatarUrlResDto> getAvatarUrl(UserAvatarUrlDto param) {
        Integer userId = param.getUserId();
        User userEntity = userService.getById(userId);
        UserAvatarUrlResDto data = new UserAvatarUrlResDto();
        data.setIcon(userEntity.getIcon());
        return new BaseResponse(MsgCodeEnum.SUCCESS, data);
    }

    @ApiOperation(value = "获取标签信息")
    @GetMapping(value = "/getFlags")
    public BaseResponse<List<FlagResDto>> getFlags(BaseReqDto param) {
        User userRedis = redisService.getUser(param.getToken());
        Integer userId = userRedis.getUid();
        User userEntity = userService.getById(userId);
        return new BaseResponse(MsgCodeEnum.SUCCESS, ParamUtils.toFlags(userEntity.getFlags()));
    }

    @ApiOperation(value = "更新用户信息", httpMethod = "POST")
    @RequestMapping(value = "/updateUser", method = RequestMethod.POST)
    public BaseResponse<UserResDto> updateUser(@RequestBody UpdateUserDto param) {
        User userRedis = redisService.getUser(param.getToken());
        Integer userId = userRedis.getUid();
        userService.updateUserByUid(userId, param.getName(), param.getIcon(), param.getBirth(), param.getHeight(), param.getWeight(), ParamUtils.listToJSONStr(param.getPhotos()), param.getIsHide(), 0, param.getIsLogout(), null, param.getResidentCity(), param.getSelfDesc(), param.getProfession(), param.getSalaryYear(), param.getWeChatAccount(), ParamUtils.listToStr(param.getFlags()));
        if (userRedis.getGender() == 1 && StringUtils.isNotBlank(param.getIcon())) {
            userService.updateVipByUid(userId, 2, LocalDateTime.now().plusMonths(Integer.valueOf(10000)));
        }
        User userEntity = userService.getUserByUserId(userId, userRedis.getLatitude(), userRedis.getLongitude());
        userEntity.setToken(param.getToken());
        if (param.getIsLogout() != null && param.getIsLogout() == 1) {
            redisService.remove(param.getToken());
        } else {
            redisService.setUser(param.getToken(), userEntity);
        }
        return new BaseResponse(MsgCodeEnum.SUCCESS, ParamUtils.userToUserResDto(userEntity));
    }

    @ApiOperation("权限校验")
    @PostMapping("/permit")
    public BaseResponse<String> add(@RequestBody PermitDto param) {
        User userRedis = redisService.getUser(param.getToken());
        Integer userId = userRedis.getUid();
        User userEntity = userService.getUserByUserId(userId, userRedis.getLongitude(), userRedis.getLatitude());
        userEntity.setToken(param.getToken());

        if (param.getMode() != null && param.getMode() == 1) {
            Integer chatCount = chatLogService.getChatCountToday(userId);
            if (userEntity.getVipLeft() > 0 && chatCount >= 50) {//50
                return new BaseResponse(MsgCodeEnum.WECHAT_COUNT_END, "当日聊天次数已用完");
            } else if (userEntity.getVipLeft() <= 0 && chatCount >= 3) {//3
                return new BaseResponse(MsgCodeEnum.WECHAT_NO_VIP, "避免广告骚扰,普通会员每日最多与三人聊天。开通会员即享畅聊");
            }
        }

        if (param.getMode() != null && param.getMode() == 2) {
            Integer chatCount = activityService.getActivityCountToMonth(userId);
            if (userEntity.getVipLeft() > 0 && chatCount >= 30) {// 30
                return new BaseResponse(MsgCodeEnum.WECHAT_COUNT_END, "当月活动发布次数已用完");
            } else if (userEntity.getVipLeft() <= 0 && chatCount >= 3) {// 3
                return new BaseResponse(MsgCodeEnum.WECHAT_NO_VIP, "当月活动发布次数已用完,前往升级会员");
            }
        }

        return new BaseResponse(MsgCodeEnum.SUCCESS, "ok");

    }
}
